//
//  Product.m
//  iFlower
//
//  Created by thohd on 7/26/10.
//  Copyright 2010 iNIL.me. All rights reserved.
//

#import "Product.h"
#import "ASIHTTPRequest.h"
#import "iFlowerAppDelegate.h"

@interface Product (Private)
- (void)loadURL:(NSURL *)url;
@end

@implementation Product

@synthesize productId = productId_;
@synthesize productCode = productCode_;
@synthesize price = price_;
@synthesize product = product_;
@synthesize shortdesc = shortdesc_;
@synthesize fulldesc = fulldesc_;
@synthesize thumbnailURL = thumbnailURL_;
@synthesize thumbnail = thumbnail_;
@synthesize amount = amount_;
@synthesize delegate;
@synthesize provider;
- (UIImage *)thumbnail
{
    if (thumbnail_ == nil)
    {
        [self loadURL:thumbnailURL_];
    }
    return thumbnail_;
}

#pragma mark -
#pragma mark ASIHTTPRequest delegate methods

- (void)requestDone:(ASIHTTPRequest *)request
{
    NSData *data = [request responseData];
    UIImage *remoteImage = [[UIImage alloc] initWithData:data];
    self.thumbnail = remoteImage;
    if ([delegate respondsToSelector:@selector(product:didLoadThumbnail:)])
    {
        [delegate product:self didLoadThumbnail:self.thumbnail];
    }
    [remoteImage release];
}

- (void)requestWentWrong:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
	NSLog(@"Error:%@", [error description]);
    if ([delegate respondsToSelector:@selector(product:couldNotLoadImageError:)])
    {
        [delegate product:self couldNotLoadImageError:error];
    }
}
- (BOOL)hasLoadedThumbnail
{
    return (thumbnail_ != nil);
}

#pragma mark -
#pragma mark Private methods

- (void)loadURL:(NSURL *)url
{
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    NSOperationQueue *queue = [iFlowerAppDelegate shareDelegate].downloadQueue;
    [queue addOperation:request];
    [request release];    
}
- (void)dealloc
{
    delegate = nil;
    [productId_ release];
    [productCode_ release];
    [price_ release];
    [product_ release];
    [shortdesc_ release];
    [fulldesc_ release];
    [thumbnailURL_ release];
    [thumbnail_ release];
    [super dealloc];
}

@end
